<?php

namespace app\admin\service;

use app\admin\model\AccessModel;
use app\admin\model\AdminModel;
use app\admin\model\MenuModel;
use app\admin\model\RoleModel;
use app\common\libs\helper\TreeHelper;
use Exception;

class RoleService extends BaseService
{
    /**
     * 获取角色下的所有子级角色ID
     *
     * @Author tanruizheng
     * @DateTime 2021-07-12
     * @param [type] $roleId
     * @param boolean $isSelf
     * @return void
     */
    public static function getChildrenRoleIdList($roleId, $isSelf = true){
        $roleList = RoleModel::select()->toArray();
        $roleList = TreeHelper::getSonNodeFromArray($roleList,$roleId,[
            'parentKey' => 'parentid'
        ]);
        $roleIds = [];
        foreach ($roleList as $key => $value) {
           $roleIds[] = $value['id'];
        }
        if($isSelf) $roleIds[] = $roleId;
        return $roleIds;
    }

    /**
     * 获取角色列表
     *
     * @Author tanruizheng
     * @DateTime 2021-07-12
     * @param array $where
     * @return void
     */
    public static function getRoleList($where = []){
        $roleList = RoleModel::where($where)->select()->toArray();
        $adminInfo = AdminService::instance()->getAdminInfo();
        if($adminInfo['role_id'] == AdminModel::SUPER_ADMIN_ROLE_ID){
            //超级管理员
            $roleList = TreeHelper::arrayToTreeList($roleList,0,[
                'idKey' => 'id',
                'parentKey' => 'parentid'
            ]);
        }else{
            $roleList = TreeHelper::arrayToTreeList($roleList,$adminInfo['role_id'],[
                'idKey' => 'id',
                'parentKey' => 'parentid'
            ]);
        }
        return self::createList($roleList);
    }

    /**
     * 添加或者编辑角色
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @param [type] $params
     * @return void
     */
    public static function addOrEditData($params){
        try {
            if(empty($params['name'])){
                return self::createFail('名称不能为空');
            }
            $data = [
                'name' => $params['name'],
                'parentid' => $params['parentid'],
                'status' => $params['status'],
                'remark' => $params['remark'] ?? '',
                'listorder' => $params['listorder'] ?? 0,
            ];
            if(isset($params['id']) && $params['id']){
                $res = RoleModel::where('id',$params['id'])->save($data);
            }else{
                $res = RoleModel::create($data);
            }
            if($res !== false){
                return self::createSuccess('保存成功');
            }
            return self::createFail('保存失败');
        } catch (Exception $e) {
            // 验证失败 输出错误信息
            return self::createFail($e->getMessage());
        }
    }

    /**
     * 获取角色详情
     *
     * @Author tanruizheng
     * @DateTime 2021-07-13
     * @param [type] $roleId
     * @return void
     */
    public static function getRoleDetail($roleId){
        $data = RoleModel::where('id',$roleId)->findOrEmpty();
        return $data;
    }

    /**
     * 角色删除
     *
     * @Author tanruizheng
     * @DateTime 2021-07-13
     * @param [type] $roleId
     * @return void
     */
    public static function roleDelete($roleId){
        if(!$roleId){
            return self::createFail('参数错误!');
        }
        $roleDetail = self::getRoleDetail($roleId);
        if(!$roleDetail){
            return self::createFail('角色不存在!');
        }
        $count = RoleModel::where('parentid',$roleId)->count();
        if($count){
            return self::createFail('该角色有下级,不能删除!');
        }
        $result = $roleDetail->delete();
        if($result !== false){
            return self::createSuccess('删除成功');
        }
        return self::createSuccess('删除失败');
    }

    /**
     * 获取角色权限
     *
     * @Author tanruizheng
     * @DateTime 2021-07-14
     * @param [type] $roleId
     * @return void
     */
    public static function getAuthorizeList($roleId){
        //获取当前登录用户的所有权限菜单
        $adminInfo = AdminService::instance()->getAdminInfo();
        $menuList = MenuService::getMenuByRole($adminInfo['role_id'])['data'];
        $trees = [];
        foreach ($menuList as &$value) {
            $array['name'] = $value['name'];
            $array['parentid'] = $value['parentid'];
            $array['value'] = $value['id'];
            //选中状态
            $array['checked'] = false;
            if(RbacService::auth($roleId,$value['app'],$value['controller'],$value['action'])['status'] == true){
                $array['checked'] = true;
            }
            $trees[] = $array;
        }
        $trees = TreeHelper::arrayToTree($trees,0,[
            'idKey' => 'value',
            'parentKey' => 'parentid',
            'childrenKey' => 'list'
        ]);
        return self::createSuccess('ok',[
            'trees' => $trees
        ],0);
    }

    /**
     * 权限更新
     *
     * @Author tanruizheng
     * @DateTime 2021-07-14
     * @param [type] $roleId
     * @param [type] $authids
     * @return void
     */
    public static function authorize($roleId,$authids){
        try {
            if(!$roleId){
                return self::createFail('参数错误');
            }
            if(!$authids){
                return self::createFail('权限不能为空');
            }
            $accessModel = new AccessModel();
            $accessModel->startTrans();
            $menuList = MenuModel::where('id','in',$authids)->select();
            $data = [];
            foreach ($menuList as &$menu) {
                $array['role_id'] = $roleId;
                $array['app'] = $menu['app'];
                $array['controller'] = $menu['controller'];
                $array['action'] = $menu['action'];
                $array['status'] = 1;
                //菜单项
                if($menu['type'] == MenuModel::TYPE_NO_AUTO){
                    $array['controller'] = $menu['controller'].$menu['id'];
                    $array['action'] = $menu['action'].$menu['id'];
                }
                $data[] = $array;
            }
            $res1 = $accessModel::where('role_id',$roleId)->delete();
            $res2 = $accessModel->insertAll($data);
            if($res1!== false && $res2){
                $accessModel->commit();
                return self::createSuccess('权限设置成功');
            }else{
                $accessModel->rollback();
                return self::createFail('权限设置失败');
            }
        } catch (Exception $e) {
            $accessModel->rollback();
            return self::createFail($e->getMessage());
        }
    }
}